package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"strconv"
)


func httpPost(url string, jsonData []byte) (string, error) {
	// 要发送POST请求的URL
	//url := "http://example.com/post"

	// 要发送的数据，这里以JSON格式为例
	//jsonData := []byte(`{
	//	"key1": "value1",
	//	"key2": "value2"
	//}`)

	// 创建一个请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}

	// 设置请求头，例如设置内容类型为JSON
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	return string(body), nil
}
// CreateDefaultKb 仅负责调用远程API创建知识库
// 参数: userId - 用户ID
// 返回: kbId - 知识库ID, error - 错误信息
func CreateDefaultKb(userId string, kbName string) (string, error) {
    var kb = struct {
        UserId string `json:"user_id"`
        KbName string `json:"kb_name"`
    }{
        UserId: userId,
        KbName: kbName,
    }

    body, err := json.Marshal(kb)
    if err != nil {
        return "", err
    }

    bodyStr, err := httpPost("http://192.168.2.37:8777/api/local_doc_qa/new_knowledge_base", body)
    if err != nil {
        return "", err
    }

    var kbResponse struct {
        Code int    `json:"code"`
        Msg  string `json:"msg"`
        Data struct {
            KbId      string `json:"kb_id"`
            KbName    string `json:"kb_name"`
            Timestamp string `json:"timestamp"`
        } `json:"data"`
    }

    if err := json.Unmarshal([]byte(bodyStr), &kbResponse); err != nil {
        return "", err
    }

    return kbResponse.Data.KbId, nil
}

type FileData struct {
    Reader   multipart.File
    Filename string
}
type UploadResponse struct {
    Code int    `json:"code"`
    Msg  string `json:"msg"`
    Data []struct {
        FileId    string `json:"file_id"`
        FileName  string `json:"file_name"`
        Status    string `json:"status"`
        Bytes     int    `json:"bytes"`
        Timestamp string `json:"timestamp"`
    } `json:"data"`
}

func UploadFilesToKb(userId string, kbId string, files []FileData, mode string, chunkSize int) (*UploadResponse, error) {
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)

    // 为每个文件创建唯一的form-data字段名
    // 添加文件，使用统一的"files"字段名
    for _, file := range files {
        part, err := writer.CreateFormFile("files", file.Filename)
        if err != nil {
            return nil, fmt.Errorf("创建文件字段失败: %v", err)
        }

        // 复制文件内容
        if _, err := io.Copy(part, file.Reader); err != nil {
            return nil, fmt.Errorf("复制文件内容失败: %v", err)
        }
		 // 上传结束后关闭文件
        file.Reader.Close()
    }

    // 添加其他字段
    _ = writer.WriteField("user_id", userId)
    _ = writer.WriteField("kb_id", kbId)
    _ = writer.WriteField("mode", mode)
    _ = writer.WriteField("chunk_size", strconv.Itoa(chunkSize))

    if err := writer.Close(); err != nil {
        return nil, err
    }

    // 创建请求
    req, err := http.NewRequest("POST", "http://192.168.2.37:8777/api/local_doc_qa/upload_files", body)
    if err != nil {
        return nil, err
    }
    req.Header.Set("Content-Type", writer.FormDataContentType())

    // 发送请求
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    // 读取响应
    respBody, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }

    // 解析响应
    var uploadResp UploadResponse
    if err := json.Unmarshal(respBody, &uploadResp); err != nil {
        return nil, err
    }

    return &uploadResp, nil
}

type KnowledgeBase struct {
    KbId   string `json:"kb_id"`
    KbName string `json:"kb_name"`
}

type ListKbResponse struct {
    Code int             `json:"code"`
    Data []KnowledgeBase `json:"data"`
}

func ListKnowledgeBase(userId string) ([]KnowledgeBase, error) {
    var request = struct {
        UserId string `json:"user_id"`
    }{
        UserId: userId,
    }

    body, err := json.Marshal(request)
    if err != nil {
        return nil, err
    }

    bodyStr, err := httpPost("http://192.168.2.37:8777/api/local_doc_qa/list_knowledge_base", body)
    if err != nil {
        return nil, err
    }

    var response ListKbResponse
    if err := json.Unmarshal([]byte(bodyStr), &response); err != nil {
        return nil, err
    }

    return response.Data, nil
}

type FileStatus struct {
    FileId        string `json:"file_id"`
    FileName      string `json:"file_name"`
    Status        string `json:"status"`
    Bytes         int    `json:"bytes"`
    ChunksNumber  int    `json:"chunks_number"`
    ContentLength int    `json:"content_length"`
    FileLocation  string `json:"file_location"`
    Timestamp     string `json:"timestamp"`
    Msg          string `json:"msg"`
}

type StatusCount struct {
    Green  int `json:"green"`
    Red    int `json:"red"`
    Gray   int `json:"gray"`
    Yellow int `json:"yellow"`
}

type ListFilesData struct {
    StatusCount StatusCount         `json:"status_count"`
    Details    []FileStatus        `json:"details"`
    PageId     int                 `json:"page_id"`
    Total      int                 `json:"total"`
    TotalPage  int                 `json:"total_page"`
}

type ListFilesResponse struct {
    Code int          `json:"code"`
    Msg  string      `json:"msg"`
    Data ListFilesData `json:"data"`
}

func ListKnowledgeBaseFiles(userId string, kbId string) (*ListFilesResponse, error) {
    var request = struct {
        UserId string `json:"user_id"`
        KbId   string `json:"kb_id"`
    }{
        UserId: userId,
        KbId:   kbId,
    }

    body, err := json.Marshal(request)
    if err != nil {
        return nil, err
    }

    bodyStr, err := httpPost("http://192.168.2.37:8777/api/local_doc_qa/list_files", body)
    if err != nil {
        return nil, err
    }

    var response ListFilesResponse
    if err := json.Unmarshal([]byte(bodyStr), &response); err != nil {
        return nil, err
    }

    return &response, nil
}

// DeleteFilesResponse 定义删除文件的响应结构
type DeleteFilesResponse struct {
    Code int    `json:"code"`
    Msg  string `json:"msg"`
}

// DeleteKnowledgeBaseFiles 删除知识库中的文件
func DeleteKnowledgeBaseFiles(userId string, kbId string, fileIds []string) (*DeleteFilesResponse, error) {
    // 构建请求体
    var request = struct {
        UserId  string   `json:"user_id"`
        KbId    string   `json:"kb_id"`
        FileIds []string `json:"file_ids"`
    }{
        UserId:  userId,
        KbId:    kbId,
        FileIds: fileIds,
    }

    // 序列化请求体
    body, err := json.Marshal(request)
    if err != nil {
        return nil, err
    }

    // 发送POST请求
    bodyStr, err := httpPost("http://192.168.2.37:8777/api/local_doc_qa/delete_files", body)
    if err != nil {
        return nil, err
    }

    // 解析响应
    var response DeleteFilesResponse
    if err := json.Unmarshal([]byte(bodyStr), &response); err != nil {
        return nil, err
    }

    return &response, nil
}

// DeleteKnowledgeBaseResponse 定义删除知识库的响应结构
type DeleteKnowledgeBaseResponse struct {
    Code int    `json:"code"`
    Msg  string `json:"msg"`
}

// DeleteKnowledgeBase 删除知识库
func DeleteKnowledgeBase(userId string, kbIds []string) (*DeleteKnowledgeBaseResponse, error) {
    // 构建请求体
    var request = struct {
        UserId string   `json:"user_id"`
        KbIds  []string `json:"kb_ids"`
    }{
        UserId: userId,
        KbIds:  kbIds,
    }

    // 序列化请求体
    body, err := json.Marshal(request)
    if err != nil {
        return nil, err
    }

    // 发送POST请求
    bodyStr, err := httpPost("http://192.168.2.37:8777/api/local_doc_qa/delete_knowledge_base", body)
    if err != nil {
        return nil, err
    }

    // 解析响应
    var response DeleteKnowledgeBaseResponse
    if err := json.Unmarshal([]byte(bodyStr), &response); err != nil {
        return nil, err
    }

    return &response, nil
}


// CleanFilesByStatusResponse 定义清理文件的响应结构
type CleanFilesByStatusResponse struct {
    Code int      `json:"code"`
    Msg  string   `json:"msg"`
    Data []string `json:"data"`
}

// CleanFilesByStatus 清理指定状态的文件
func CleanFilesByStatus(userId string, status string, kbIds []string) (*CleanFilesByStatusResponse, error) {
    // 构建请求体
    var request = struct {
        UserId string   `json:"user_id"`
        Status string   `json:"status"`
        KbIds  []string `json:"kb_ids"`
    }{
        UserId: userId,
        Status: status,
        KbIds:  kbIds,
    }

    // 序列化请求体
    body, err := json.Marshal(request)
    if err != nil {
        return nil, err
    }

    // 发送POST请求
    bodyStr, err := httpPost("http://192.168.2.37:8777/api/local_doc_qa/clean_files_by_status", body)
    if err != nil {
        return nil, err
    }

    // 解析响应
    var response CleanFilesByStatusResponse
    if err := json.Unmarshal([]byte(bodyStr), &response); err != nil {
        return nil, err
    }

    return &response, nil
}

// RenameKnowledgeBaseResponse 重命名知识库响应结构体
type RenameKnowledgeBaseResponse struct {
    Code int    `json:"code"`
    Msg  string `json:"msg"`
}

// RenameKnowledgeBase 重命名知识库
func RenameKnowledgeBase(userId string, kbId string, newKbName string) (*RenameKnowledgeBaseResponse, error) {
    // 构建请求体
    var request = struct {
        UserId    string `json:"user_id"`
        KbId      string `json:"kb_id"`
        NewKbName string `json:"new_kb_name"`
    }{
        UserId:    userId,
        KbId:      kbId,
        NewKbName: newKbName,
    }

    // 序列化请求体
    body, err := json.Marshal(request)
    if err != nil {
        return nil, err
    }

    // 发送POST请求
    bodyStr, err := httpPost("http://192.168.2.37:8777/api/local_doc_qa/rename_knowledge_base", body)
    if err != nil {
        return nil, err
    }

    // 解析响应
    var response RenameKnowledgeBaseResponse
    if err := json.Unmarshal([]byte(bodyStr), &response); err != nil {
        return nil, err
    }

    return &response, nil
}